const db = wx.cloud.database();
const command = db.command;
Page({
  /** 
   * 页面的初始数据 
   */
  data: {
    swiperTab: [{
        text: '待接单',
      },
      {
        text: '维修中',
      },
      {
        text: '已完成',
      },
    ],

    nowloginuser: '',
    workername: '',
    swiperTabIndex: 0,
    Hei: '',
    waitinglist: [],
    fixinglist: [],
    finishlist: [],

    // 下拉操作是否被触发
    triggered: false,

  },

  // 顶部导航的点击事件
  changeTab: function (event) {
    // console.log(event.target.dataset.index)
    this.setData({
      swiperTabIndex: event.target.dataset.index
    })
  },

  // 内容的切换事件
  changeContent: function (event) {
    // console.log(event)
    this.setData({
      swiperTabIndex: event.detail.current
    })
  },

  // 先从缓存读取当前登录的工人的名字，并存储到data中
  getuserid: function () {
    wx.getStorage({
      key: 'nickName',
    }).then(res => {
      // console.log(res.data);
      this.setData({
        workername: res.data
      })
    })
  },

  // 从数据库拿到状态为已提交的内容，并存储到data中的waitinglist数组中
  get_waitinginfo: function () {
    db.collection("fix_desc")
      .where({
        fix_state: '已提交'
      })
      .orderBy('fix_submit_time','desc')
      .get()
      .then(res => {
        console.log(res.data);
        this.setData({
          waitinglist: res.data
        })
      })

  },

  // 从数据库拿到状态是维修中的数据，并存储到data中的fixinglist数组中
  get_fixinginfo: function () {
    db.collection("fix_desc")
      .where({
        worker: this.data.workername,
        fix_state: '维修中'
      })
      .orderBy('receiveorder_time','desc')
      .get()
      .then(res => {
        // console.log(res.data);
        this.setData({
          fixinglist: res.data
        })
      })
  },

  // 从数据库拿到状态是已完成的数据，并存储到data中的finishlist数组中
  get_finishinfo: function () {
    db.collection("fix_desc")
      .where({
        worker: this.data.workername,
        fix_state: '已完成'
      })
      .orderBy('fix_finishtime','desc')
      .get()
      .then(res => {
        // console.log(res.data);
        this.setData({
          finishlist: res.data
        })
      })
  },

  //自定义下拉刷新控件被下拉 
  onPulling(e) {
    // console.log('onPulling:', e)
  },

  // 自定义下拉刷新被触发
  onRefresh() {
    if (this._freshing) return
    this._freshing = true
    setTimeout(() => {
      this.getuserid();
      this.get_waitinginfo();
      this.get_fixinginfo();
      this.get_finishinfo();
      this.setData({
        triggered: false,
      })
      this._freshing = false
    }, 2000)
  },

  // 进入页面自动刷新
  onRefreshnow() {
    if (this._freshing) return
    this._freshing = true
    setTimeout(() => {
      this.getuserid();
      this.get_waitinginfo();
      this.get_fixinginfo();
      this.get_finishinfo();
      this.setData({
        triggered: false,
      })
      this._freshing = false
    }, 100)
  },

  // 自定义下拉刷新被复位
  onRestore(e) {
    console.log('onRestore:', e)
  },

  // 自定义下拉刷新被中止
  onAbort(e) {
    console.log('onAbort', e)
  },

  // 点击查看待接单详情的操作包括跳转等
  show_fixdetail: function (e) {
    // console.log(e.currentTarget.dataset.index);
    wx.setStorage({
      data: this.data.waitinglist[e.currentTarget.dataset.index],
      key: 'fix_descdetail',
    })
    wx.navigateTo({
      url: '../../pages/worker_fixdesc/worker_fixdesc',
    })
  },

  // 点击查看维修中的订单详情
  show_fixingdetail: function (e) {
    // console.log(e.currentTarget.dataset.index);
    wx.setStorage({
      data: this.data.fixinglist[e.currentTarget.dataset.index],
      key: 'fix_descdetail',
    })
    wx.navigateTo({
      url: '../../pages/worker_fixingdesc/worker_fixingdesc',
    })
  },

  // 点击查看维修完成的订单详情
  show_finishdesc: function (e) {
    console.log(e.currentTarget.dataset.index);
    wx.setStorage({
      data: this.data.finishlist[e.currentTarget.dataset.index],
      key: 'fix_descdetail',
    })
    wx.navigateTo({
      url: '../../pages/worker_finishdesc/worker_finishdesc',
    })
  },

  // 立即接单的按钮
  pickorder: async function (e) {
    console.log("点击接单的序号是", e.currentTarget.dataset.index);
    console.log("点击接单的详情是", this.data.waitinglist[e.currentTarget.dataset.index]);

    var time = new Date().toLocaleString();
    wx.showModal({
      title: '提示',
      content: '是否确认接单？',
    }).then(res => {
      if (res.confirm) {
        // 在数据库中修改状态为已接单
        // 接单时间
        wx.cloud.callFunction({
          name: 'update',
          data: {
            options: 'pickorder',
            docid: this.data.waitinglist[e.currentTarget.dataset.index]._id,
            state: '维修中',
            wokername: this.data.workername,
            receiveorder_time: time,
          }
        }).then(res => {
          console.log("接取订单成功");
          console.log(res.result.event);
          this.onRefreshnow();
          wx.showToast({
            title: '接单成功',
            mask:true,
            duration:2000
          })
        })
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    })
  },

  // 维修完成的按钮
  finishfix:function(e){
    console.log("点击确认的序号是", e.currentTarget.dataset.index);
    console.log("点击确认的详情是", this.data.fixinglist[e.currentTarget.dataset.index]);
    var time = new Date().toLocaleString();
    wx.showModal({
      title: '提示',
      content: '是否已经完成维修',
    }).then(res=>{
      if(res.confirm){
        // 在数据库中修改状态为已接单
        // 接单时间
        wx.cloud.callFunction({
          name: 'update',
          data: {
            options: 'finishfix',
            docid: this.data.fixinglist[e.currentTarget.dataset.index]._id,
            state: '已完成',
            wokername: this.data.workername,
            finishtime: time,
          }
        }).then(res => {
          console.log("维修完成");
          console.log(res.result.event);
          this.onRefreshnow();
          wx.showToast({
            title: '维修完成',
            mask:true,
            duration:2000
          })
        })
      }else if(res.cancel){
        console.log("用户点击取消");
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onRefreshnow();
    this.getuserid();
    // this.get_waitinginfo();
    // this.get_fixinginfo();
    // this.get_finishinfo();
    // console.log(options)
    this.setData({
      swiperTabIndex: options.index,
      Hei: wx.getSystemInfoSync().windowHeight
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }


})